package com.lzx.answer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzx.answer.entity.Problem;
import com.lzx.answer.entity.Reply;
import com.lzx.answer.entity.vo.NicknameVO;
import com.lzx.answer.entity.vo.OssVO;
import com.lzx.answer.entity.vo.ProblemParams;
import com.lzx.answer.entity.vo.UploadProblem;
import com.lzx.answer.mapper.ProblemMapper;
import com.lzx.answer.mapper.ReplyMapper;
import com.lzx.answer.service.ProblemService;
import com.lzx.common.utils.ExcelUtils;
import com.lzx.common.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lzx
 * @since 2022-10-05
 */
@Service
public class ProblemServiceImpl extends ServiceImpl<ProblemMapper, Problem> implements ProblemService {
    @Resource
    private ProblemMapper problemMapper;

    @Resource
    private ReplyMapper replyMapper;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    //获取所有问题
    @Override
    public R getList(int current, int size) {
        Page<Problem> page = new Page<>(current, size);
        problemMapper.selectPage(page, null);
        Map<String, Object> map = new HashMap<>();
        List<Problem> list = page.getRecords();//当前页数据
        long total = page.getTotal();//总记录数
        map.put("list", list);
        map.put("total", total);
        return R.ok().data("map", map);
    }

    //上传问题
    @Override
    public R upload(UploadProblem uploadProblem) {
        Problem problem = new Problem();
        BeanUtils.copyProperties(uploadProblem, problem);
        problem.setCreateTime(new Date());
        problemMapper.insert(problem);
        rocketMQTemplate.convertAndSend("problem-topic", "上传问题");
        return R.ok().message("上传成功");
    }

    //根据问题id获取问题信息
    @Override
    public R getProblemById(Long id) {
        Problem problem = problemMapper.selectById(id);
        return R.ok().data("problem", problem);
    }

    //统计作者的回答数、文章数
    @Override
    public R statistical(Long userId) {
        QueryWrapper<Reply> replyQueryWrapper = new QueryWrapper<>();
        replyQueryWrapper.eq("user_id", userId);
        List<Reply> replyList = replyMapper.selectList(replyQueryWrapper);
        //TODO 统计作者文章数
        return R.ok().data("replyCount", replyList.size());
    }

    //上传问题的用户是否解决问题
    @Override
    public R isSolveProblem(Long userId, Long problemId) {
        QueryWrapper<Problem> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("id", problemId);
        Problem problem = problemMapper.selectOne(wrapper);
        problem.setSolve(Objects.equals(problem.getSolve(), "1") ? "0" : "1");
        problemMapper.updateById(problem);
        return R.ok().message("更新成功");
    }

    //根据点赞数查询前十条问题
    @Override
    public R rankBeforeTen() {
        QueryWrapper<Problem> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("like_count").last("limit 10");
        List<Problem> list = problemMapper.selectList(wrapper);
        return R.ok().data("list", list);
    }

    //获取当前用户关注的人发表的问题
    @Override
    public List<Problem> getUserAttentionPublishProblem(List<Integer> userIds) {
        List<Problem> problems = new ArrayList<>();
        for (Integer userId : userIds) {
            QueryWrapper<Problem> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            List<Problem> problemList = problemMapper.selectList(wrapper);
            problems.addAll(problemList);
        }
        //根据发表时间排序(降序)
        problems.sort((t1, t2) -> t2.getCreateTime().compareTo(t1.getCreateTime()));
        return problems;
    }

    //获取当前用户发表的问题
    @Override
    public R getProblemListByUserId(Long userId) {
        QueryWrapper<Problem> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<Problem> list = problemMapper.selectList(wrapper);
        return R.ok().data("list", list);
    }

    //获取所有问题
    @Override
    public R getProblemList(int current, int size) {
        Page<Problem> page = new Page<>(current, size);
        problemMapper.selectPage(page, null);
        Map<String, Object> map = new HashMap<>();
        List<Problem> list = page.getRecords();//当前页数据
        long total = page.getTotal();//总记录数
        map.put("list", list);
        map.put("total", total);
        return R.ok().data("map", map);
    }

    //新增问题
    @Override
    public R addProblem(Problem problem) {
        problemMapper.insert(problem);
        rocketMQTemplate.convertAndSend("problem-topic", "新增问题");
        return R.ok().message("新增成功");
    }

    //修改问题
    @Override
    public R updateProblem(Problem problem) {
        problem.setUpdateTime(new Date());
        problemMapper.updateById(problem);
        rocketMQTemplate.convertAndSend("problem-topic", "修改问题");
        return R.ok().message("修改成功");
    }

    //删除问题
    @Override
    public R deleteProblem(List<Long> ids) {
        problemMapper.deleteBatchIds(ids);
        rocketMQTemplate.convertAndSend("problem-topic", "删除问题");
        return R.ok().message("删除成功!");
    }

    //根据id获取问题信息
    @Override
    public R getProblem(Long id) {
        Problem problem = problemMapper.selectById(id);
        return R.ok().data("problem", problem);
    }

    //搜索
    @Override
    public R searchProblem(ProblemParams problemParams) {
        QueryWrapper<Problem> wrapper = new QueryWrapper<>();
        if (StringUtils.isNoneBlank(problemParams.getTitle())) {
            wrapper.like("title", problemParams.getTitle());
        }
        if (StringUtils.isNoneBlank(problemParams.getNickname())) {
            wrapper.like("nickname", problemParams.getNickname());
        }
        if (problemParams.getMinViews() != null) {
            wrapper.ge("views", problemParams.getMinViews());
        }
        if (problemParams.getMaxViews() != null) {
            wrapper.le("views", problemParams.getMaxViews());
        }
        if (problemParams.getMinLikeCount() != null) {
            wrapper.ge("like_count", problemParams.getMinLikeCount());
        }
        if (problemParams.getMaxLikeCount() != null) {
            wrapper.le("like_count", problemParams.getMaxLikeCount());
        }
        if (problemParams.getMinReply() != null) {
            wrapper.ge("reply", problemParams.getMinReply());
        }
        if (problemParams.getMaxReply() != null) {
            wrapper.le("reply", problemParams.getMaxReply());
        }
        if (StringUtils.isNoneBlank(problemParams.getSolve())) {
            wrapper.eq("solve", problemParams.getSolve());
        }
        if (problemParams.getStartTime() != null && !"".equals(problemParams.getStartTime())) {
            wrapper.ge("create_time", problemParams.getStartTime());
        }
        if (problemParams.getEndTime() != null && !"".equals(problemParams.getEndTime())) {
            wrapper.le("create_time", problemParams.getEndTime());
        }
        List<Problem> list = problemMapper.selectList(wrapper);
        return R.ok().data("list", list);
    }

    //导出
    @Override
    public void exportProblem(HttpServletResponse response) {
        List<Problem> list = problemMapper.selectList(null);
        ExcelUtils.export(response, "问题信息", Problem.class, list);
    }

    //修改用户头像(问题)
    @Transactional
    @Override
    public String updateAvatarToProblem(OssVO ossVO) {
        QueryWrapper<Problem> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", ossVO.getId());
        List<Problem> problemList = problemMapper.selectList(wrapper);
        for (Problem problem : problemList) {
            problem.setAvatar(ossVO.getAvatar());
            problemMapper.updateById(problem);
        }
        return "修改成功";
    }

    //修改用户昵称(问题)
    @Transactional
    @Override
    public String updateNicknameToProblem(NicknameVO nicknameVO) {
        QueryWrapper<Problem> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", nicknameVO.getId());
        List<Problem> problemList = problemMapper.selectList(wrapper);
        for (Problem problem : problemList) {
            problem.setNickname(nicknameVO.getNickname());
            problemMapper.updateById(problem);
        }
        return "修改成功";
    }

    //用户修改头像或昵称 es同步
    @Override
    public List<Problem> getUserProblemListToES(Long userId) {
        QueryWrapper<Problem> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return problemMapper.selectList(wrapper);
    }

    //获取浏览量最多的十个问答
    @Override
    public R getTopTenProblem() {
        QueryWrapper<Problem> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("views").last("limit 10");
        List<Problem> list = problemMapper.selectList(wrapper);
        return R.ok().data("list", list);
    }
}
